/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package powerpongpc;

import java.awt.Image;
import java.io.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 *
 * @author alwynster
 */
public class PowerPongPC {

    public static Bluetooth getBt() { return bt; }
    /**
     * @param args the command line arguments
     */
    static Bluetooth bt;
    static App app;
    public static void main(String[] args)  {
        try {
            app = new App();
            // TODO code application logic here
            
            bt = new Bluetooth();
    //        form.append(bt.getStringItem());
            bt.InitBluetooth();
            bt.CreateServer();
            
            InputStreamReader ir = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(ir);

            String send = br.readLine();
            do
            {
                bt.SendString(send);
                send = br.readLine();
            }
            while(!send.equals("exit"));
            
            
        } catch (IOException ex) {
            Logger.getLogger(PowerPongPC.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
       class Bluetooth implements DiscoveryListener { //CommandListener, 
        OutputStream os;
        InputStream is; 
        StreamConnection sc;
    
        LocalDevice localDev;
        DiscoveryAgent discAgent;
        Vector devices, unaddedDevices;
        RemoteDevice remDevice;

//        StringItem stringItem;
        int devicesFound = 0;
        String[] namesArr, addressArr;
        
        final int readLength = 10;

//        List serversList;
//        javax.microedition.lcdui.Command cancelCommand, selectCommand;
//        Displayable oldScreen;

        final UUID uuid = new UUID(0xABCDEF);
        private boolean inquiryActive;

        Thread readThread;
        /*
        * Initiate bluetooth stack
         * returns null if initiates successfully, otherwise an error message
        */
       public void InitBluetooth()
       {
           try
           {
               if(localDev == null)
               {
                   localDev = LocalDevice.getLocalDevice();
                   discAgent = localDev.getDiscoveryAgent();
               }
               System.out.println("Bluetooth initialized");
//               stringItem.setText("Bluetooth initialized");
           }
           catch(Exception b)
           {
               System.out.println("Cannot init bluetooth stack. ");
//               stringItem.setText("Cannot init bluetooth stack. ");
           }
       }

       // host a server over the bluetooth
       public void CreateServer()
       {
           String conString = null;
            try {
                UUID uuid = new UUID(0x1101);
                conString = "btspp://localhost:" + "2D26618601FB47C28D9F10B8EC891363" + ";authenticate=false;encrypt=false;name=PowerPongService";
                
                System.out.println(conString);
                
//                this.stringItem.setText("Bluetooth server created");
                StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open(conString, Connector.READ_WRITE);
                System.out.println("Bluetooth server created");
                StreamConnection connection = notifier.acceptAndOpen();
                System.out.println("Accept and open");
                os = connection.openOutputStream();
                is = connection.openInputStream();
                
                System.out.println("Streams created");
                
                readThread = ReadThread();
                readThread.start();
            
            } catch (IOException ex) {
                System.out.println(conString);
//                        stringItem.setText(conString);
            }
       }

       // Close bluetooth connection
       public void close()
       {
        try {
            os.flush();
            os.close();
            is.close();
        } catch (IOException ex) {
            Logger.getLogger(Bluetooth.class.getName()).log(Level.SEVERE, null, ex);
        }
       }
       
       public void SendString(String dataString)
       {
            while(dataString.length() < readLength) { dataString = dataString + "0"; }
            if(dataString.length() > readLength) dataString = dataString.substring(0, readLength);
            try {
                os.write(dataString.getBytes());
                os.flush();
            } catch (IOException ex) {
                Logger.getLogger(Bluetooth.class.getName()).log(Level.SEVERE, null, ex);
            }
       }
       
       // be a client and look for a bluetooth server
       public void FindServer(String serverName)
       {
           System.out.println("Finding server");
//           stringItem.setText("Finding server");
           if(serverName == null)
           {
               if(devices == null)
                   devices = new Vector();
               else if(devices.isEmpty())
                   devices.removeAllElements();

               if(unaddedDevices == null)
                   unaddedDevices = new Vector();

               try
               {
                   discAgent.startInquiry(DiscoveryAgent.GIAC, this);
                   inquiryActive = true;

                   Image[] img = null;
//                   serversList = new List("Choose server", Choice.EXCLUSIVE);//, namesArr, img);
//                   serversList.addCommand(getCancelCommand());
//                   serversList.addCommand(getSelectCommand());
//                   serversList.setCommandListener(this);
//                   showDisplayable(serversList);
               }
               catch(Exception e)
               {
                   System.out.println("Could not start inquiry: " + e.getMessage());
//                   stringItem.setText("Could not start inquiry: " + e.getMessage());
               }
           }
       }

//       //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringItem ">
//       /**
//        * Returns an initiliazed instance of stringItem component.
//        * @return the initialized component instance
//        */
//       public StringItem getStringItem() {
//           if (stringItem == null) {
//               // write pre-init user code here
//               stringItem = new StringItem("Bluetooth output: ", "No output yet");
//               // write post-init user code here
//           }
//           return stringItem;
//       }
//       //</editor-fold>

       // found server on bluetooth
        public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
            try
            {
                if(devices.indexOf(rd) == -1)
                {
                    devicesFound++;
                    System.out.println(devicesFound + " device(s) discovered");
//                    stringItem.setText(devicesFound + " device(s) discovered");
                    System.out.println("Choose server (" + devicesFound + ")");
//                    serversList.setTitle("Choose server (" + devicesFound + ")");

                    devices.addElement(rd);
                    System.out.println(rd.getFriendlyName(false));
//                            serversList.append(rd.getFriendlyName(false), null);
                }
            }
            catch(Exception c)
            {
                unaddedDevices.addElement(rd);
            }

        }

        // done searching for bluetooth devices
        public void inquiryCompleted(int i) {
            inquiryActive = false;
            System.out.println("Inquiry completed: " + devicesFound);
//                    stringItem.setLabel("Inquiry completed: " + devicesFound);

            namesArr = new String[devices.size()];
            addressArr = new String[devices.size()];

            for(int y = 0 ; y < unaddedDevices.size() ; y++)
            {
                try
                {
                    System.out.println(((RemoteDevice) unaddedDevices.elementAt(y)).getFriendlyName(true));
                    servers.add(((RemoteDevice) unaddedDevices.elementAt(y)).getFriendlyName(true)); 
//                    serversList.append(((RemoteDevice) unaddedDevices.elementAt(y)).getFriendlyName(true), null);
                }
                catch (IOException ex)
                {
                }
            }
        }
Vector servers = new Vector();
        
//        //<editor-fold defaultstate="collapsed" desc=" Generated Getter: getCancelCommand ">
//        /**
//         * Returns an initialized instance of cancelCommand component.
//         * @return the initialized component instance
//         */
//        public Command getCancelCommand() {
//           if (cancelCommand == null) {
//                // write pre-init user code here
//              cancelCommand = new Command("Cancel", Command.CANCEL, 0);
//                // write post-init user code here
//           }
//           return cancelCommand;
//        }
//        //</editor-fold>
//
//        //<editor-fold defaultstate="collapsed" desc=" Generated Getter: getSelectCommand ">
//        /**
//         * Returns an initialized instance of selectCommand component.
//         * @return the initialized component instance
//         */
//        public Command getSelectCommand () {
//           if (selectCommand == null) {
//                // write pre-init user code here
//              selectCommand = new Command("Select", Command.OK, 0);
//                // write post-init user code here
//           }
//           return selectCommand;
//        }
//        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Unused bluetooth functions">
        public void serviceSearchCompleted(int i, int i1) {
//            stringItem.setText("Service search completed");
        }
        
        public void servicesDiscovered(int i, ServiceRecord[] srs) {
//            stringItem.setText("Services discovered");
        }
        //</editor-fold>
        
        //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">
        /**
         * Called by a system to indicated that a command has been invoked on a particular displayable.
         * @param command the Command that was invoked
         * @param displayable the Displayable where the command was invoked
         */
//        public void commandAction(Command command, Displayable displayable) {
//           // write pre-action user code here
//            if (displayable == serversList) 
//            {
//                if (command == cancelCommand) {
//                    revertDisplayable();
//                }
//                else if (command == selectCommand)
//                {
//                    revertDisplayable();
//                    if(inquiryActive)
//                    {
//                        discAgent.cancelInquiry(this);
//                    }
//                    if(serversList.getSelectedIndex() > -1)
//                    {
        public void NewServer()
        {
//                        String selIndex = serversList.getString(serversList.getSelectedIndex());
            System.out.println("New server: \nSelect server");
            InputStreamReader ir = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(ir);
            
            int selIndex = -1; 
            try {
                selIndex = Integer.parseInt(br.readLine());
            } catch (IOException ex) {
                Logger.getLogger(PowerPongPC.class.getName()).log(Level.SEVERE, null, ex);
            }
//                        serversList.setTitle("Selected: " + selIndex);
            System.out.println("Selected: " + selIndex);
//                        remDevice = (RemoteDevice) devices.elementAt(serversList.getSelectedIndex());
                        remDevice = (RemoteDevice) devices.elementAt(selIndex);
                        try {
//                            stringItem.setText(remDevice.getFriendlyName(true) + " " + remDevice.getBluetoothAddress());
                            System.out.println(remDevice.getFriendlyName(true) + " " + remDevice.getBluetoothAddress());
                        } catch (IOException ex) {
                            System.out.println("Cannot retrieve Remote Device details.");
//                                    stringItem.setText("Cannot retrieve Remote Device details.");
                        }


                        String conString = null;
                        try
                        {
                            conString = "btspp://" + remDevice.getBluetoothAddress() + ":1;authenticate=false;encrypt=false";
                            System.out.println(conString);
//                                    serversList.setTitle(conString);
                            sc = (StreamConnection) Connector.open(conString, Connector.READ);
                            is = sc.openInputStream();
                            // byte[] bytes = new byte[1024];
                            // int read = is.read(bytes);
                            int b = is.read();
                            System.out.println("read " + b);
//                            serversList.setTitle("read " + b);
                            is.close();
//                            OutputStream os = sc.openOutputStream();
//                            os.write(0);
//                            os.flush();
                            sc.close();
                            
                            // InputStream  is = sc.openInputStream();
                        }
                        catch (IOException ex) {
                            System.out.println("ERROR: " + ex.getMessage());
//                                    stringItem.setText("ERROR: " + ex.getMessage());
                        }
        }
//                    }
//                }
//            }
           // write post-action user code here
//        }
        //</editor-fold>

        private Thread ReadThread()
        {
            return new Thread()
            {
                public void run()
                {
                    try {
                        String readString = "";
                        byte[] byte_arr = new byte[readLength];
                        int r = 0;
                        while(!readString.equals("stop"))
                        {
                            r = is.read(byte_arr, 0, readLength);
                            readString = new String(byte_arr, 0, readLength);
                            if(r != -1)
                            {
                                if(readString.charAt(0) == 'P')
                                    System.out.println("Position: (" + r + ") " + readString.substring(1));
                                else if(readString.charAt(0) == 'C')
                                {
                                    PowerPongPC.app.setClient((int)(Double.parseDouble(readString.substring(1)) * 100));
                                    System.out.println("Client: (" + r + ") " + readString.substring(1));
                                }
                                else
                                    System.out.println("read: (" + r + ") " + readString);
                            }
//                            stringItem.setText("read: " + readString);
                            byte_arr = new byte[1024];
                        }
                        is.close();
                        // int b = is.read();
                    } catch (IOException ex) {
//                        serversList.setTitle(ex.getMessage());
                        System.out.println(ex.getMessage());
                    }
                }
            };
        }
   }
